<template>
  <div class="page-wrap">
    <el-card shadow="never">
      <div class="toolbar">
        <el-date-picker v-model="range" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        <el-button @click="refresh">刷新</el-button>
      </div>

      <el-alert type="info" show-icon title="根据销售出库记录统计，若商品缺少款号/颜色/尺码，将以名称代替" class="mb-12" />

      <el-table :data="rows" border stripe>
        <el-table-column prop="styleNo" label="款号" width="140" />
        <el-table-column prop="color" label="颜色" width="120" />
        <el-table-column v-for="sz in sizes" :key="sz" :prop="`size_${sz}`" :label="sz" width="90" />
        <el-table-column prop="totalQty" label="合计" width="100" />
        <el-table-column prop="amount" label="金额(估)" width="120" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStockStore } from '@/stores/stock.js'
import { useProductStore } from '@/stores/product.js'

const stock = useStockStore()
const product = useProductStore()
const range = ref([])
const sizes = ref([])
const rows = ref([])

onMounted(() => {
  if (!stock.stockList.length) stock.initializeStock()
  if (!product.productList.length) product.initializeProducts()
  refresh()
})

function inRange(dateIso){
  if (!range.value || range.value.length !== 2) return true
  const [start, end] = range.value
  const d = new Date(dateIso).toISOString().slice(0,10)
  return (!start || d >= start) && (!end || d <= end)
}

function refresh(){
  const outbound = stock.getStockHistory(null, 'outbound').filter(r => inRange(r.date))
  const pidToProduct = Object.fromEntries(product.productList.map(p => [p.id, p]))
  const sizeSet = new Set()
  const map = {}
  outbound.forEach(r => {
    const p = pidToProduct[r.productId]
    const styleNo = p?.styleNo || p?.code || r.productName
    const color = p?.color || '未设'
    const size = p?.size || '均码'
    sizeSet.add(size)
    const key = `${styleNo}__${color}`
    if (!map[key]) map[key] = { styleNo, color, qtyBySize: {}, totalQty: 0, amount: 0 }
    const price = Number(p?.salePrice || 0)
    map[key].qtyBySize[size] = (map[key].qtyBySize[size] || 0) + Number(r.quantity || 0)
    map[key].totalQty += Number(r.quantity || 0)
    map[key].amount += Number(r.quantity || 0) * price
  })
  sizes.value = Array.from(sizeSet)
  rows.value = Object.values(map).map(x => {
    const row = { styleNo: x.styleNo, color: x.color, totalQty: x.totalQty, amount: Number(x.amount.toFixed(2)) }
    sizes.value.forEach(sz => { row[`size_${sz}`] = x.qtyBySize[sz] || 0 })
    return row
  })
}
</script>

<style scoped>
.page-wrap { padding: 16px; }
.toolbar { display: flex; gap: 12px; align-items: center; }
.mb-12 { margin-bottom: 12px; }
</style>


